package YAPclient;

import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

import YAPenvironment.YAPconstant;
import YAPenvironment.YAPconstant.Command;
import YAPenvironment.YAPerrorCode;


/**
 * A class for the menu bars used in {@link FormLobbyOverview} and {@link FormGameLobby}
 */

public class YAPMenuBar extends JMenuBar implements ActionListener{
	
	
	private static final long serialVersionUID = -7142063037913144011L;

	private String sep = YAPconstant.C_SEPARATOR;
    
	private javax.swing.JMenu game;
    private javax.swing.JMenuItem miHighScore;
    private javax.swing.JMenuItem miClearChatHistory;
    private javax.swing.JMenu options;
    private javax.swing.JMenuItem miChangeName;
    private javax.swing.JCheckBoxMenuItem miSound;
    private javax.swing.JMenu quit;
    private javax.swing.JMenuItem miQuitYAP;
    private javax.swing.JMenuItem miDisconnect;
    private javax.swing.JMenuItem miQuitLobby;
    private javax.swing.JMenu help;
    private javax.swing.JMenuItem miOpenManual;
    private ManualTXT manual;
	
    
    /**
     * Creates a new instance of YAPMenuBar
     * @param lobby use true, if this menu bar is intended to be used in an in-lobby form (i.e. in an instance of
     * {@link FormGameLobby}), false if it's going to be used in an instance of {@link FormgameLobby}
     */
	public YAPMenuBar(boolean lobby){
	
		super();
		
		game = new javax.swing.JMenu("Game");
		miHighScore =  new javax.swing.JMenuItem("High Scores");
    	miHighScore.addActionListener(this);
    	game.add(miHighScore);
    	this.add(game);
    
   	   	options = new javax.swing.JMenu("Options");
   		miChangeName = new javax.swing.JMenuItem("Change Name");
   		miChangeName.addActionListener(this);
    	miClearChatHistory = new javax.swing.JMenuItem("Clear Chat History");
    	miClearChatHistory.addActionListener(this);
    	
    	
    	miSound = new javax.swing.JCheckBoxMenuItem ("Sound");
    	if(DataModul.clPlayer.getSound())
    		miSound.setSelected(true);
    	miSound.addActionListener(this);
    	if(lobby==false)
    		options.add(miChangeName);	
    	options.add(miClearChatHistory);
       	options.add(miSound);
        this.add(options);
    	
        help = new javax.swing.JMenu("Help");
    	miOpenManual = new javax.swing.JMenuItem("Open Manual");
    	miOpenManual.addActionListener(this);
    	help.add(miOpenManual);
    	this.add(help);
    	
    	quit = new javax.swing.JMenu("Quit");
    	miQuitYAP = new javax.swing.JMenuItem("Quit YAP");
		miDisconnect = new javax.swing.JMenuItem("Disconnect from Server");
		miQuitLobby =  new javax.swing.JMenuItem("Quit Lobby");
		miDisconnect.addActionListener(this);
    	miQuitYAP.addActionListener(this);
    	miQuitLobby.addActionListener(this);
    	if(lobby==true)
    		quit.add(miQuitLobby);
    	quit.add(miDisconnect);
    	quit.add(miQuitYAP);
    	this.add(quit); 	
	
	}

	
	/**
	 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 */
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource()==miChangeName){
			DataModul.flo.openChangeNameDialog();
		}else if(e.getSource()==miQuitYAP){
			DataModul.disconnect();
			System.exit(1);
		}else if(e.getSource()==miDisconnect){
			DataModul.disconnect();
			System.out.println("Client: disconnected");
			if(DataModul.flo != null)
				DataModul.flo.dispose();
			if(DataModul.fgl != null)
				DataModul.fgl.dispose();
			new YAPgame();
		}else if(e.getSource()==miHighScore){
			DataModul.parseThread.writeMessage(Command.getHighScore.toString()+sep);
		}else if(e.getSource() == miClearChatHistory){
			DataModul.flo.clearChatHistory();
		}else if(e.getSource()==miQuitLobby){
			DataModul.parseThread.writeMessage(Command.leaveLobby.toString()+sep);
		}else if(e.getSource()==miOpenManual){
			if(Desktop.isDesktopSupported()){
				new ManualPDF().start();
			}
			else{
				if(manual!=null)
					manual.dispose();
				new ManualTXT();
			}
		}else if(e.getSource()==miSound){
			if(miSound!=null){
				if(miSound.isSelected()){
					//System.out.println("an");
					DataModul.clPlayer.setSound(true);
				}
				else{
					//System.out.println("ab");
					DataModul.clPlayer.setSound(false);
				}
			}
//			DataModul.flo.openSoundDialog();
		}		
		
	}

	private static class ManualPDF extends Thread{
		
		public void run() {
			try{
				InputStream is = YAPconstant.class.getResourceAsStream( "Manual.pdf" ); 
				File file = File.createTempFile("User_Guide", ".pdf"); 
				file.deleteOnExit();
				
				copy(is,file);
	
				Desktop.getDesktop().open(file);
			}catch (Exception e){
				if(YAPconstant.C_DEBUG) { e.printStackTrace(); }
			}
		}
		
		void copy(InputStream in, File dst) throws IOException {
			OutputStream out = new FileOutputStream(dst);
			
			byte[] buf = new byte[1024];
			int len;
			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
			in.close();
			out.close();
		}
	}
	
	@SuppressWarnings("serial")
	private static class ManualTXT extends JFrame{
		
		JTextArea jTextArea;
		
		ManualTXT(){
				createGUI();
				
				InputStream is = null;
				BufferedReader br = null;
				String line;
				
				try { 

					ManualTXT manual = new ManualTXT();
					
					is = YAPconstant.class.getResourceAsStream("Manual.txt");
					br = new BufferedReader(new InputStreamReader(is));
					while (null != (line = br.readLine())) {
						manual.updateTextArea(line+"\n");
					}
				}
				catch (Exception e1) {
					if(YAPconstant.C_DEBUG){ e1.printStackTrace(); }
					setErrorMessage();
				}
				finally {
					try {
						if (br != null) br.close();
						if (is != null) is.close();
					}
					catch (Exception e2) {
						if(YAPconstant.C_DEBUG){ e2.printStackTrace(); }
					}
				}
				
		}
		
		private void updateTextArea(final String text) {
			  SwingUtilities.invokeLater(new Runnable() {
			    public void run() {
			      jTextArea.append(text);
			    }
			  });
		}
		
		private void createGUI() {
			this.setTitle("YAP Manual");
			
			JScrollPane jScrollPane = new javax.swing.JScrollPane();
	        jTextArea = new javax.swing.JTextArea();

	        jTextArea.setColumns(20);
	        jTextArea.setRows(5);
	        jTextArea.setEditable(false);
	        jScrollPane.setViewportView(jTextArea);

	        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
	        getContentPane().setLayout(layout);
	        layout.setHorizontalGroup(
	            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(layout.createSequentialGroup()
	                .addContainerGap()
	                .addComponent(jScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
	                .addContainerGap())
	        );
	        layout.setVerticalGroup(
	            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
	                .addContainerGap()
	                .addComponent(jScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE)
	                .addContainerGap())
	        );
	        
	        pack();
	        
	        setLocationRelativeTo(null);
	        this.setVisible(true);
		}
	}
	

	@SuppressWarnings("unchecked")
	private static void setErrorMessage(){
		DataModul.flo.getChatListModel().addElement(YAPerrorCode.getErrorMsg(-102));
	}

}